package com.onejson.ojmall.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.onejson.ojmall.common.domain.ResponseDTO;
import com.onejson.ojmall.model.form.ExcelImportForm;
import io.swagger.annotations.Api;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/excel")
@Api(tags = "pdf管理")
public class ExcelController {

    /**
     * 批量导入带图片
     * @throws Exception
     */
    @PostMapping("/importAssetImg")
    public ResponseDTO<String> importAssetImg(@RequestParam MultipartFile file) throws IOException {
        List<ExcelImportForm> dataList;
        try {
            // 读取字段
            dataList = EasyExcel.read(file.getInputStream()).head(ExcelImportForm.class)
                    .sheet()
                    .doReadSync();
        } catch (IOException e) {
            throw new RuntimeException("数据格式存在问题，无法读取");
        }

        if (CollectionUtils.isEmpty(dataList)) {
            return ResponseDTO.userErrorParam("数据为空");
        }

        // 初始化计数器，用于记录当前处理的Excel行号
        int count = 0;
        // 遍历数据列表，处理每一行的Excel数据
        for (ExcelImportForm importForm : dataList) {
            // 处理Excel中的图片，获取对应的行的图片，并将图片保存到本地
            String localImagePath = handleExcelImage(file, count);
            // 将图片路径设置到Excel导入表单中
            importForm.setPhotoPath(localImagePath);
            // 计数器自增，用于记录下一行的Excel数据
            count++;
        }

        return ResponseDTO.okMsg("成功导入" + dataList.size() + "条");
    }

    /**
     * 处理Excel中的图片 获取对应的行的图片
     *
     * @param file
     * @param rowCount
     * @return
     */
    private String handleExcelImage(MultipartFile file, int rowCount) throws IOException {
        if (ObjectUtil.isEmpty(file)) {
            throw new RuntimeException("文件不能为空");
        }
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        XSSFSheet sheet = workbook.getSheetAt(0);
        Map<String, PictureData> pictures = getPictures(sheet);

        rowCount++;
        // 获取图片所在的列号，从0开始数
        String columnNum = "1";
        String imageKey = rowCount + ":" + columnNum;

        if (pictures.containsKey(imageKey)) {
            PictureData pictureData = pictures.get(imageKey);
            byte[] image = pictureData.getData();
            String projectPath = System.getProperty("user.dir");
            String photoPath = "/upload/public/common/" + rowCount;
            String dateStr = DateUtil.format(new Date(), "yyyy-MM-dd");
            String fileName = "excel_img" + "_" + dateStr + "_" + ".png";
            String uploadPath = projectPath + photoPath + fileName;

            FileUtil.writeBytes(image, uploadPath);
            String ip = InetAddress.getLocalHost().getHostAddress();
            int port = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUri().getPort();
            return "http://" + ip + ":" + port + photoPath + fileName;
        }

        return "";
    }

    /**
     * 获取图片数据
     * @param sheet
     * @return
     */
    private static Map<String, PictureData> getPictures(XSSFSheet sheet) {
        Map<String, PictureData> picMap = new HashMap<>();
        List<XSSFShape> list = sheet.getDrawingPatriarch().getShapes();

        if (CollectionUtil.isEmpty(list)) {
            return picMap;
        }
        for (XSSFShape hssfShape : list) {
            // 过滤出图片的数据
            if (hssfShape instanceof XSSFPicture) {
                XSSFPicture xssfPicture = (XSSFPicture) hssfShape;
                XSSFClientAnchor xssfClientAnchor = (XSSFClientAnchor) xssfPicture.getAnchor();
                PictureData pictureData = xssfPicture.getPictureData();
                picMap.put(xssfClientAnchor.getRow1() + ":" + xssfClientAnchor.getCol1(), pictureData);
            }
        }
        return picMap;
    }
}